package com.taotao.order.service.impl;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.manager.mapper.TbOrderItemMapper;
import com.taotao.manager.mapper.TbOrderMapper;
import com.taotao.manager.mapper.TbOrderShippingMapper;
import com.taotao.manager.pojo.TbOrderItem;
import com.taotao.manager.pojo.TbOrderShipping;
import com.taotao.order.jedis.JedisClient;
import com.taotao.order.pojo.OrderInfo;
import com.taotao.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbOrderItemMapper orderItemMapper;
    @Autowired
    private TbOrderShippingMapper shippingMapper;
    @Autowired
    private JedisClient jedis;

    @Value("${GEN_ORDER_ID_KEY}")
    private String GEN_ORDER_ID_KEY;
    @Value("${GEN_ORDER_ID_INIT}")
    private Long GEN_ORDER_ID_INIT;
    @Value("${GEN_ORDER_ITEM_ID_KEY}")
    private String GEN_ORDER_ITEM_ID_KEY;

    @Override
    public TaotaoResult createOrder(OrderInfo info) {
        //插入订单表--通过redis的incr生成订单id--补全其他属性
        //插入订单项表--通过redis的incr生成订单项id--补全其他属性
        //插入订单物流表--设置订单id,补全其他属性
        Long incr = jedis.incr(GEN_ORDER_ID_KEY);
        String orderId = checkItemId(incr).toString();
        info.setOrderId(orderId);
        info.setCreateTime(new Date());
        info.setPostFee("0");
        info.setStatus(1);//状态 1:未付款  2:已付款  3:未发货  4:已发货  5:交易成功 6:交易关闭
        info.setUpdateTime(info.getCreateTime());
        orderMapper.insert(info);
        List<TbOrderItem> orderItems = info.getOrderItems();
        for (TbOrderItem orderItem : orderItems) {
            String orderItemId = jedis.incr(GEN_ORDER_ITEM_ID_KEY).toString();
            orderItem.setId(orderItemId);
//            orderItem.setItemId(orderItem.getItemId());
            orderItem.setOrderId(orderId);
            orderItemMapper.insert(orderItem);
        }
        TbOrderShipping orderShipping = info.getOrderShipping();
        orderShipping.setOrderId(orderId);
        orderShipping.setCreated(info.getCreateTime());
        orderShipping.setUpdated(info.getCreateTime());
        shippingMapper.insert(orderShipping);
        return TaotaoResult.ok(orderId);
    }

    private Long checkItemId(Long incr) {
        if (incr < GEN_ORDER_ID_INIT) {
            synchronized (OrderServiceImpl.class) {
                incr = Long.parseLong(jedis.get(GEN_ORDER_ID_KEY));
                if (incr < GEN_ORDER_ID_INIT) {
                    jedis.set(GEN_ORDER_ID_KEY, GEN_ORDER_ID_INIT + "");
                    incr = GEN_ORDER_ID_INIT;
                } else {
                    incr = jedis.incr(GEN_ORDER_ID_KEY);
                }
            }
        }
        return incr;
    }
}
